package com.lvgang.springbootrabbitmq.deadqueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lvgang
 */
@Configuration
public class RabbitDeadQueueConfig {

    private static Logger logger = LoggerFactory.getLogger(RabbitDeadQueueConfig.class);

    /**
        * Queue 可以有4个参数
     *      1.队列名
     *      2.durable       持久化消息队列 ,rabbitmq重启的时候不需要创建新的队列 默认true
     *      3.auto-delete   表示消息队列没有在使用时将被自动删除 默认是false
     *      4.exclusive     表示该消息队列是否只在当前connection生效,默认是false
     */

    /**
     * 死信队列跟交换机类型没有关系 不一定为directExchange  不影响该类型交换机的特性.
     *
     * @return the exchange
     */
    @Bean
    public Exchange deadLetterExchange() {
        logger.info("创建deadLetterExchange成功");
        return ExchangeBuilder.directExchange(RabbitDeadQueueConstant.DL_EXCHANGE).durable(true).build();
    }

    /**
     * 声明一个死信队列.
     * x-dead-letter-exchange   对应  死信交换机
     * x-dead-letter-routing-key  对应 死信队列
     *
     * @return the queue
     */
    @Bean
    public Queue deadLetterQueue() {
        logger.info("创建deadLetterQueue成功");
        Map<String, Object> args = new HashMap<>(2);
//       x-dead-letter-exchange    声明  死信交换机
        args.put("x-dead-letter-exchange", RabbitDeadQueueConstant.DL_EXCHANGE);
//       x-dead-letter-routing-key    声明 死信路由键
        args.put("x-dead-letter-routing-key", RabbitDeadQueueConstant.REDIRECT_QUEUE_KEY);
        return QueueBuilder.durable(RabbitDeadQueueConstant.DL_QUEUQ).withArguments(args).build();
    }

    /**
     * 定义死信队列转发队列.
     *
     * @return the queue
     */
    @Bean
    public Queue redirectQueue() {
        logger.info("创建redirectQueue成功");
        return QueueBuilder.durable(RabbitDeadQueueConstant.REDIRECT_QUEUE).build();
    }

    /**
     * 死信路由通过 DL_KEY 绑定键绑定到死信队列上.
     * @return the binding
     */
    @Bean
    public Binding deadLetterBinding() {
        logger.info("绑定deadLetterQueue到deadLetterExchange成功");
        return new Binding(RabbitDeadQueueConstant.DL_QUEUQ, Binding.DestinationType.QUEUE,
                RabbitDeadQueueConstant.DL_EXCHANGE, RabbitDeadQueueConstant.DL_QUEUQ_KEY, null);

    }

    /**
     * 死信路由通过 KEY_R 绑定键绑定到最终处理队列上.
     * @return the binding
     */
    @Bean
    public Binding redirectBinding() {
        logger.info("绑定redirectQueue到deadLetterExchange成功");
        return new Binding(RabbitDeadQueueConstant.REDIRECT_QUEUE, Binding.DestinationType.QUEUE,
                RabbitDeadQueueConstant.DL_EXCHANGE, RabbitDeadQueueConstant.REDIRECT_QUEUE_KEY, null);
    }

}